package dk.sdu.mmmi.opn.assignment3easy.server;

import java.rmi.AlreadyBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;

/**
 * Catalogue server using Java RMI
 * @author ups
 */
public class Server {

	// Approximate distances to various locations in kilometers
	protected static final int DISTANCE_NZ_KM = 18000; 
	protected static final int DISTANCE_NY_KM = 6000;
	protected static final int DISTANCE_PARIS_KM = 950;
	protected static final int DISTANCE_CPH_KM = 150;
	protected static final int DISTANCE_LOCALHOST = 0;
	
	/**
	 * Object registry name 
	 */
	public static final String NAME = "catalogue";
	
	/**
	 * Registry port
	 */
	public static final int PORT = 12345;
	
	/**
	 * When larger than zero, logging operation takes time corresponding to this value in milliseconds
	 */
	public static int SIMULATED_LATENCY_MS = DISTANCE_NZ_KM*2*1000/300000; // Approximate lightspeed round-trip in milliseconds
	
	/**
	 * When true, increase verboseness og logging
	 */
	public static boolean VERBOSE_LOGGING = true; 
	
	/**
	 * Logging operation, to be called for all remote operations; secretly introduces a delay corresponding
	 * to SIMULATED_LATENCY_MS
	 * @param severe when true indicates a severe problem, otherwise not
	 * @param message the message to log
	 */
	public static void log(boolean severe, String message) {
		if(severe)
			System.err.println("***LOG "+message);
		else if(VERBOSE_LOGGING)
			System.out.println("LOG: "+message);
		if(SIMULATED_LATENCY_MS>0) try {
			Thread.sleep(SIMULATED_LATENCY_MS);
		} catch(InterruptedException exn) {
			System.err.println("***LOG: unexpected operation during simulated latency wait");
		}
	}
	
	/**
	 * Start server
	 */
	public static void main(String argv[]) {
		try {
			LocateRegistry.createRegistry(PORT).bind(NAME,new CatalogueImpl());
		} catch (RemoteException | AlreadyBoundException e) {
			throw new Error("Server launch failed: "+e);
		}
		System.out.println("Server running");
		if(SIMULATED_LATENCY_MS>0) System.out.println("Simulating latency of "+SIMULATED_LATENCY_MS+"ms");
		if(VERBOSE_LOGGING) System.out.println("Verbose logging activated");
	}

}
